package com.quartz.utils;

import org.quartz.*;
import org.quartz.impl.triggers.CronTriggerImpl;
import org.quartz.impl.triggers.SimpleTriggerImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 *
 */
@Service
public class QuartzScheduleUtil {

    private static String JOB_GROUP_NAME = "FH_JOBGROUP_NAME"; // 任务组
    private static String TRIGGER_GROUP_NAME = "FH_TRIGGERGROUP_NAME"; // 触发器组

    @Autowired
    private Scheduler scheduler;

    /**
     * 获取定时器调度实例
     *
     * @return 实例对象
     */
	/*public static QuartzManager getInstance() {
		if (null == instance) {
			synchronized (QuartzManager.class) {
				if (null == instance) {
					instance = new QuartzManager();
				}
			}
		}
		return instance;
	}*/

    /**
     * 无限重复任务
     *
     * 功能： 添加一个定时任务
     *
     * @param jobName
     *            任务名
     * @param triggerName
     *            触发器名
     * @param jobClass
     *            任务的类类型 eg:TimedMassJob.class
     * @param cron
     *            时间设置 表达式，参考quartz说明文档
     */
    public void addJob(String jobName,
                       String triggerName,
                       Class<? extends Job> jobClass,
                       String cron,
                       Map<String,Object> jobParams,
                       Map<String,Object> triggerParams) throws SchedulerException {
        TriggerKey triggerKey =TriggerKey.triggerKey(triggerName,TRIGGER_GROUP_NAME);
        try {
            Trigger triggerS = scheduler.getTrigger(triggerKey);
            if(triggerS == null){
            //cfb.set
            // 任务名，任务组，任务执行类
            JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(jobName, JOB_GROUP_NAME).build();

            //添加任务参数
            this.saveJobParams(jobParams,jobDetail);
            TriggerBuilder<Trigger> triggerBuilder = TriggerBuilder.newTrigger();
            // 触发器名,触发器组
            triggerBuilder.withIdentity(triggerName, TRIGGER_GROUP_NAME);
            triggerBuilder.startNow();
            // 触发器时间设定
            triggerBuilder.withSchedule(CronScheduleBuilder.cronSchedule(cron));

            // 创建Trigger对象
            CronTrigger trigger = (CronTrigger) triggerBuilder.build();
            //添加任务参数
            this.saveTriggerParams(triggerParams,trigger);
            // 调度容器设置JobDetail和Trigger
            scheduler.scheduleJob(jobDetail, trigger);
            //启动
            scheduler.start();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    // 添加任务参数
    public void  saveJobParams(Map<String,Object> jobParams,JobDetail jobDetail){
            if (jobParams != null) {
        Iterator<Map.Entry<String, Object>> entries = jobParams.entrySet().iterator();
        while (entries.hasNext()) {
            Map.Entry<String, Object> entry = entries.next();
            String key = entry.getKey();
            Object value = entry.getValue();
            System.out.println(key + ":" + value);
            jobDetail.getJobDataMap().put(key, value);
        }
      }
    }

    // 添加触发器参数
    public void  saveTriggerParams(Map<String,Object> triggerParams,CronTrigger trigger){
        if (triggerParams != null) {
            Iterator<Map.Entry<String, Object>> entries = triggerParams.entrySet().iterator();
            while (entries.hasNext()) {
                Map.Entry<String, Object> entry = entries.next();
                String key = entry.getKey();
                Object value = entry.getValue();
                System.out.println(key + ":" + value);
                trigger.getJobDataMap().put(key, value);
            }
        }
    }

    /**
     * 以時間間隔的方式添加任務
     * @param jobName
     * @param triggerName
     * @param jobClass
     */

//    public void addJobByInterval(String jobName,
//                                 String triggerName,
//                                 Class<? extends Job> jobClass,
//                                 String cron,
//                                 String... string) {
//        try {
//            // 任务名，任务组，任务执行类
//            JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(jobName, JOB_GROUP_NAME).build();
//            // 触发器
//            TriggerKey triggerKey =TriggerKey.triggerKey(triggerName,TRIGGER_GROUP_NAME);
//            Trigger trigger = scheduler.getTrigger(triggerKey);
//            trigger= TriggerBuilder
//                    .newTrigger()
//                    .withSchedule(CronScheduleBuilder.cronSchedule(cron))
//            // 触发器名,触发器组
//            triggerBuilder.startNow();
//            // 触发器时间设定
//            triggerBuilder.withSchedule(SimpleScheduleBuilder.repeatHourlyForever((int)objects[1]));
//            //triggerBuilder.withSchedule(SimpleScheduleBuilder.repeatSecondlyForever((int)objects[1]));
//            // 创建Trigger对象
//            Trigger trigger =   triggerBuilder.build();
//            Map<String, Object> map = DateUtils.msUtilsDate(string[1], string[2]);
//            trigger.getStartTime().setTime((Long) map.get("statusTime"));
//            trigger.getEndTime().setTime((Long) map.get("endTime"));
//            // 调度容器设置JobDetail和Trigger
//            scheduler.scheduleJob(jobDetail, trigger);
//        } catch (Exception e) {
//            throw new RuntimeException(e);
//        }
//    }

    /**
     * 功能：修改一个任务的触发时间
     *
     * @param jobName
     * @param jobGroupName
     * @param triggerName
     *            触发器名
     * @param triggerGroupName
     *            触发器组名
     *            时间设置，参考quartz说明文档
     */
    public void modifyJobTimeByInterval(String jobName, String jobGroupName, String triggerName, String triggerGroupName,Object... objects) {
        try {
            int repeatHour=(int) objects[1];
            Date beginTime = (Date) objects[2],endTime=(Date) objects[3];
            TriggerKey triggerKey = TriggerKey.triggerKey(triggerName, triggerGroupName);
            SimpleTriggerImpl trigger = (SimpleTriggerImpl) scheduler.getTrigger(triggerKey);
            if (trigger == null) {
                return;
            }
            long repeatMi = repeatHour*60*60*1000;
            //long repeatMi = repeatHour*1000;
            Date oldBeginTime  = trigger.getStartTime();trigger.getStartTime();
            Date oldEndTime = trigger.getEndTime();
            long oldRepeatHour = trigger.getRepeatInterval();
            if(repeatMi!=oldRepeatHour||!(beginTime.equals(oldBeginTime))||!(endTime.equals(oldEndTime))){
                // 触发器
                TriggerBuilder<Trigger> triggerBuilder = TriggerBuilder.newTrigger();
                // 触发器名,触发器组
                triggerBuilder.withIdentity(triggerName, triggerGroupName);
                triggerBuilder.startNow();
                // 触发器时间设定
                //triggerBuilder.withSchedule(SimpleScheduleBuilder.repeatSecondlyForever((int)objects[1]));
                triggerBuilder.withSchedule(SimpleScheduleBuilder.repeatHourlyForever((int) objects[1]));
                // 创建Trigger对象
                trigger = (SimpleTriggerImpl) triggerBuilder.build();
                trigger.setStartTime((Date)objects[2]);
                trigger.setEndTime((Date)objects[3]);
                // 方式一 ：修改一个任务的触发时间
                scheduler.rescheduleJob(triggerKey, trigger);
            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public void modifyJobTime(String jobName, String jobGroupName, String triggerName, String triggerGroupName,String cron) {
        try {
            TriggerKey triggerKey = TriggerKey.triggerKey(triggerName, triggerGroupName);
            CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
            if (trigger == null) {
                return;
            }
            String oldTime = trigger.getCronExpression();
            if (!oldTime.equalsIgnoreCase(cron)) {
                // 触发器
                TriggerBuilder<Trigger> triggerBuilder = TriggerBuilder.newTrigger();
                // 触发器名,触发器组
                triggerBuilder.withIdentity(triggerName, triggerGroupName);
                triggerBuilder.startNow();
                // 触发器时间设定
                triggerBuilder.withSchedule(CronScheduleBuilder.cronSchedule(cron));
                // 创建Trigger对象
                trigger = (CronTrigger) triggerBuilder.build();
                // 方式一 ：修改一个任务的触发时间
                scheduler.rescheduleJob(triggerKey, trigger);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 功能: 移除一个任务
     *
     * @param jobName
     * @param jobGroupName
     * @param triggerName
     * @param triggerGroupName
     */
    public void removeJob(String jobName, String jobGroupName, String triggerName, String triggerGroupName) {
        try {
            TriggerKey triggerKey = TriggerKey.triggerKey(triggerName, triggerGroupName);
            // 停止触发器
            scheduler.pauseTrigger(triggerKey);
            // 移除触发器
            scheduler.unscheduleJob(triggerKey);
            // 删除任务
            scheduler.deleteJob(JobKey.jobKey(jobName, jobGroupName));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @Description:暂停一个任务
     * @param jobName
     * @param jobGroupName
     */
    public void pauseJob(String jobName, String jobGroupName) {
        JobKey jobKey = JobKey.jobKey(jobName, jobGroupName);
        try {
            scheduler.pauseJob(jobKey);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }

    /**
     * @Description:恢复一个任务
     * @param jobName
     * @param jobGroupName
     */
    public void resumeJob(String jobName, String jobGroupName) {
        JobKey jobKey = JobKey.jobKey(jobName, jobGroupName);
        try {
            scheduler.resumeJob(jobKey);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }




    /**
     *
     * 功能：启动所有定时任务
     */
    public void startJobs() {
        try {
            if (scheduler.isStarted()) {
                System.out.println("定时器已启动。");
            } else {
                scheduler.start();
            }
        } catch (SchedulerException e1) {
            e1.printStackTrace();
        }
    }

    /**
     * 功能：关闭所有定时任务
     */
    public void shutdownJobs() {
        try {
            if (!scheduler.isShutdown()) {
                scheduler.shutdown();
            }
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }

    public static List<String> getRecentTriggerTime(String cron) {
        List<String> list = new ArrayList<String>();
        try {
            CronTriggerImpl cronTriggerImpl = new CronTriggerImpl();
            cronTriggerImpl.setCronExpression(cron);
            // 这个是重点，一行代码搞定
            List<Date> dates = TriggerUtils.computeFireTimes(cronTriggerImpl, null, 8);
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            for (Date date : dates) {
                list.add(dateFormat.format(date));
            }

        } catch (ParseException e) {
            e.printStackTrace();
        }
        return list;
    }

}
